"use client";
import React, { useState, useEffect, useRef } from "react";
import Image from "next/image";
import {
  Skeleton,
  Alert,
  Empty,
  Modal,
  Pagination,
  Breadcrumb,
  Button,
  Spin,
} from "antd";
import { useRouter, useSearchParams } from "next/navigation";
import { createStyles } from "antd-style";
import { userCenterGet5, userCenterGet4 } from "@/apis";
import SearchBar from "@/components/SearchBar";
import { PlayCircleOutlined, LoadingOutlined } from "@ant-design/icons";

// 定义接口返回的数据结构
interface ScienceCover {
  category: string | null;
  attachmentName: string;
  attachmentAddress: string;
}

interface ScienceAttachment {
  category: string | null;
  attachmentName: string;
  attachmentAddress: string;
}

interface ScienceItem {
  id: number;
  categoryId: number;
  categoryName: string;
  type: number;
  scienceName: string;
  introduction?: string;
  isPopular: boolean;
  listStatus: number;
  uploadTime: string;
  uploadUser: string;
  covers: ScienceCover[];
  attachments: ScienceAttachment[];
}

// 修正分类接口数据类型（匹配实际返回）
interface CategoryItem {
  id: number;
  categoryName: string; // 修正字段名
  createTime: string; // 新增实际返回的字段
}

// 自定义样式
const useStyle = createStyles(({ prefixCls, css }) => ({
  breadcrumbContainer: css`
    margin-bottom: 16px;
    width: 100%;
  `,
  categoryButton: css`
    position: relative;
    border-radius: 4px;
    transition: all 0.3s ease;

    &.${prefixCls}-btn {
      background: #fff;
      color: #333;
      border: 1px solid #d9d9d9;
      margin-right: 8px;

      &:hover:not([disabled]) {
        border-color: #2570ff;
        color: #2570ff;
        background: #f0f7ff;
      }
    }
  `,
  categoryButtonActive: css`
    &.${prefixCls}-btn {
      background: linear-gradient(135deg, #2570ff, #1890ff);
      color: #fff;
      border: none;
      box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
      margin-right: 8px;

      &:hover:not([disabled]) {
        box-shadow: 0 4px 12px rgba(24, 144, 255, 0.4);
        background: linear-gradient(135deg, #1890ff, #096dd9);
      }
    }
  `,
  paginationContainer: css`
    margin-top: 24px;
    width: 100%;
    display: flex;
    justify-content: center;
  `,
  categoryContainer: css`
    margin: 16px 0;
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  `,
  videoContainer: css`
    position: relative;
    width: 100%;
    padding-top: 56.25%; /* 16:9 比例 */
  `,
  videoOverlay: css`
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba(0, 0, 0, 0.5);
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      background-color: rgba(0, 0, 0, 0.7);
    }
  `,
  playIcon: css`
    font-size: 48px;
    color: white;
    transition: all 0.3s ease;

    &:hover {
      transform: scale(1.1);
    }
  `,
  videoLoading: css`
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba(0, 0, 0, 0.1);
  `,
  masonryContainer: css`
    column-gap: 1rem;
    @media (max-width: 640px) {
      columns: 1;
    }
    @media (min-width: 641px) and (max-width: 768px) {
      columns: 2;
    }
    @media (min-width: 769px) and (max-width: 1024px) {
      columns: 3;
    }
    @media (min-width: 1025px) and (max-width: 1280px) {
      columns: 4;
    }
    @media (min-width: 1281px) {
      columns: 5;
    }
  `,
}));

export default function Pqps() {
  const router = useRouter();
  const { styles } = useStyle();
  const searchParams = useSearchParams();
  const [searchKeyword, setSearchKeyword] = useState("");
  // 状态管理
  const [scienceList, setScienceList] = useState<ScienceItem[]>([]);
  // 将初始状态设置为空数组，确保始终可迭代
  const [categories, setCategories] = useState<CategoryItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [categoryLoading, setCategoryLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [categoryError, setCategoryError] = useState<string | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedItem, setSelectedItem] = useState<ScienceItem | null>(null);
  const [videoLoading, setVideoLoading] = useState(false);
  const videoRef = useRef<HTMLVideoElement>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalItems, setTotalItems] = useState(0);
  const [pageSize] = useState(20); // 减少每页数量，更适合无限滚动
  const [currentCategory, setCurrentCategory] = useState("all");
  const [hasMore, setHasMore] = useState(true);
  const loadMoreRef = useRef<HTMLDivElement>(null);
  const [imageAspectRatios, setImageAspectRatios] = useState<
    Record<number, string>
  >({});

  // 处理图片和附件 URL
  const getFullImageUrl = (relativePath: string) => {
    if (!relativePath) return "/images/radio01.png";
    if (relativePath.startsWith("http")) return relativePath;
    const ossBaseUrl = "https://oss.tz-group.com/";
    const cleanPath = relativePath.startsWith("/")
      ? relativePath.slice(1)
      : relativePath;
    return `${ossBaseUrl}${cleanPath}`;
  };

  // 判断是否为视频文件
  const isVideoFile = (url: string) => {
    const videoExtensions = [".mp4", ".webm", ".ogg", ".mov", ".avi", ".mkv"];
    return videoExtensions.some((ext) => url.toLowerCase().endsWith(ext));
  };

  // 获取科普分类（修正数据解析）
  const fetchCategories = async () => {
    setCategoryLoading(true);
    setCategoryError(null);
    try {
      const response = await userCenterGet4({
        baseURL: "/api/proxy",
      });
      setCategories(
        Array.isArray(response?.data?.data) ? response.data.data : []
      );
    } catch (err) {
      setCategoryError("获取分类失败");
      console.error("分类请求错误:", err);
      setCategories([]); // 出错时也确保是数组
    } finally {
      setCategoryLoading(false);
    }
  };

  // 获取科普数据
  const fetchScienceData = async (isLoadMore = false) => {
    if (isLoadMore) {
      setLoading(true);
    } else {
      setLoading(true);
      setError(null);
    }

    try {
      const params = {
        "condition.keyword": searchKeyword.trim() || "",
        "condition.categoryId":
          currentCategory !== "all" ? currentCategory : "",
        "condition.page": isLoadMore ? currentPage : 1,
        "condition.size": pageSize,
      };

      const queryString = new URLSearchParams(
        Object.entries(params).reduce((acc, [key, value]) => {
          if (value !== undefined) acc[key] = String(value);
          return acc;
        }, {} as Record<string, string>)
      ).toString();

      const response = await userCenterGet5({
        url: `/user_center/science?${queryString}`,
        baseURL: "/api/proxy",
      });

      const newData = response?.data?.data?.data || [];
      const total = response?.data?.data?.total || 0;

      if (isLoadMore) {
        setScienceList((prev) => [...prev, ...newData]);
      } else {
        setScienceList(newData);
        setCurrentPage(1);
      }

      setTotalItems(total);
      if (isLoadMore) {
        setHasMore(scienceList.length + newData.length < total);
      } else {
        setHasMore(newData.length < total);
      }
    } catch (err) {
      setError("网络异常，无法加载科普数据");
      console.error("科普请求错误:", err);
    } finally {
      setLoading(false);
    }
  };

  // 加载更多数据
  const loadMore = () => {
    if (!loading && hasMore) {
      setCurrentPage((prev) => prev + 1);
    }
  };

  // 分类切换处理
  const handleCategoryChange = (categoryId: string) => {
    setCurrentCategory(categoryId);
    setCurrentPage(1);
    setScienceList([]);
    setHasMore(true);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  // 初始化加载和监听变化
  useEffect(() => {
    fetchCategories();
  }, []);

  useEffect(() => {
    fetchScienceData();
  }, [currentCategory, searchKeyword]);

  useEffect(() => {
    if (currentPage > 1) {
      fetchScienceData(true);
    }
  }, [currentPage]);

  useEffect(() => {
    const keyword = searchParams.get("condition.keyword") || "";
    setSearchKeyword(keyword);
  }, [searchParams]);

  // 无限滚动监听
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting && hasMore && !loading) {
          loadMore();
        }
      },
      { threshold: 0.1 }
    );

    if (loadMoreRef.current) {
      observer.observe(loadMoreRef.current);
    }

    return () => {
      if (loadMoreRef.current) {
        observer.unobserve(loadMoreRef.current);
      }
    };
  }, [hasMore, loading]);

  // 处理科普项点击 - 打开视频模态框
  const handleItemClick = (item: ScienceItem) => {
    setSelectedItem(item);
    setIsModalOpen(true);
  };

  // 视频加载处理
  const handleVideoLoadStart = () => {
    setVideoLoading(true);
  };

  const handleVideoLoadedData = () => {
    setVideoLoading(false);
  };

  const handleVideoError = () => {
    setVideoLoading(false);
    console.error("视频加载失败");
  };

  // 关闭模态框时停止视频播放
  const handleModalClose = () => {
    if (videoRef.current) {
      videoRef.current.pause();
    }
    setIsModalOpen(false);
    setSelectedItem(null);
    setVideoLoading(false);
  };

  // 当弹窗打开时自动播放视频
  useEffect(() => {
    if (isModalOpen && videoRef.current) {
      // 延迟一点时间确保视频元素完全加载
      const timer = setTimeout(() => {
        if (videoRef.current) {
          videoRef.current.play().catch((err) => {
            console.log("自动播放失败，需要用户交互:", err);
          });
        }
      }, 100);

      return () => clearTimeout(timer);
    }
  }, [isModalOpen]);

  // 获取视频URL
  const getVideoUrl = () => {
    if (!selectedItem || !selectedItem.attachments?.length) return null;

    // 优先查找视频附件
    const videoAttachment = selectedItem.attachments.find((att) =>
      isVideoFile(att.attachmentAddress)
    );

    // 如果没有视频附件，使用第一个附件
    return videoAttachment
      ? getFullImageUrl(videoAttachment.attachmentAddress)
      : getFullImageUrl(selectedItem.attachments[0].attachmentAddress);
  };

  // 高亮搜索关键词的组件
  const HighlightText = ({
    text,
    keyword,
  }: {
    text: string;
    keyword: string;
  }) => {
    if (!keyword.trim()) {
      return <span>{text}</span>;
    }

    const regex = new RegExp(`(${keyword})`, "gi");
    const parts = text.split(regex);

    return (
      <span>
        {parts.map((part, index) => {
          const isMatch = regex.test(part);
          return isMatch ? (
            <mark
              key={index}
              className="bg-yellow-200 text-yellow-900 px-1 rounded font-medium"
            >
              {part}
            </mark>
          ) : (
            <span key={index}>{part}</span>
          );
        })}
      </span>
    );
  };

  // 处理图片加载，动态计算宽高比
  const handleImageLoad = (
    item: ScienceItem,
    event: React.SyntheticEvent<HTMLImageElement>
  ) => {
    const img = event.currentTarget;
    const aspectRatio = img.naturalWidth / img.naturalHeight;

    setImageAspectRatios((prev) => ({
      ...prev,
      [item.id]: aspectRatio > 1 ? "16/9" : "9/16",
    }));
  };

  // 检测视频类型并返回合适的样式
  const getVideoCoverStyle = (item: ScienceItem) => {
    const storedAspectRatio = imageAspectRatios[item.id];

    if (storedAspectRatio) {
      return {
        aspectRatio: storedAspectRatio,
        maxHeight: storedAspectRatio === "9/16" ? "500px" : "300px",
        objectFit: "cover" as const,
      };
    }

    // 回退到基于名称的判断
    const isMobileVideo =
      item.scienceName?.includes("移动") ||
      item.scienceName?.includes("手机") ||
      item.scienceName?.includes("竖屏") ||
      item.categoryName?.includes("移动");

    if (isMobileVideo) {
      return {
        aspectRatio: "9/16",
        maxHeight: "500px",
        objectFit: "cover" as const,
      };
    } else {
      return {
        aspectRatio: "16/9",
        maxHeight: "300px",
        objectFit: "cover" as const,
      };
    }
  };

  // 构建面包屑
  const getBreadcrumbItems = () => {
    return [
      {
        title: (
          <span onClick={() => router.push("/")} className="cursor-pointer">
            首页
          </span>
        ),
        key: "home",
      },
      {
        title: (
          <span
            onClick={() => router.push("/quality")}
            className="cursor-pointer"
          >
            质量科普
          </span>
        ),
        key: "quality",
        isCurrent: true,
      },
    ];
  };

  // 渲染分类按钮
  const renderCategoryButtons = () => {
    if (categoryLoading) {
      return (
        <div className="flex gap-2">
          {[1, 2, 3, 4].map((i) => (
            <Skeleton.Button key={i} size="default" style={{ width: 80 }} />
          ))}
        </div>
      );
    }

    if (categoryError) {
      return (
        <Alert
          message={categoryError}
          type="error"
          showIcon
          style={{ marginBottom: 16 }}
        />
      );
    }

    const allCategories = [
      { id: "all", name: "全部" },
      ...(Array.isArray(categories)
        ? categories.map((cat) => ({
            id: cat.id.toString(),
            name: cat.categoryName,
          }))
        : []),
    ];

    return allCategories.map((category) => (
      <Button
        key={category.id}
        onClick={() => handleCategoryChange(category.id)}
        className={
          currentCategory === category.id
            ? styles.categoryButtonActive
            : styles.categoryButton
        }
      >
        {category.name}
      </Button>
    ));
  };

  // 渲染单个科普项
  const renderScienceItem = (item: ScienceItem) => {
    const imageUrl = item.covers?.[0]?.attachmentAddress
      ? getFullImageUrl(item.covers[0].attachmentAddress)
      : "/images/radio01.png";

    // 检查是否有视频附件
    const hasVideo =
      item.attachments?.some((att) => isVideoFile(att.attachmentAddress)) ||
      false;

    return (
      <div
        key={item.id}
        className="bg-white shadow-md flex flex-col cursor-pointer overflow-hidden hover:shadow-lg transition-shadow duration-300 break-inside-avoid mb-4"
        onClick={() => handleItemClick(item)}
      >
        <div className="relative overflow-hidden">
          <Image
            src={imageUrl}
            alt={item.scienceName || "科普图片"}
            width={600}
            height={400}
            className="w-full h-auto object-cover transition-all duration-300 ease-in-out hover:scale-105"
            priority={false}
            style={getVideoCoverStyle(item)}
            onLoad={(e) => handleImageLoad(item, e)}
          />

          {/* 如果有视频，显示播放按钮 */}
          {hasVideo && (
            <div className={styles.videoOverlay}>
              <PlayCircleOutlined className={styles.playIcon} />
            </div>
          )}
        </div>
        <div className="p-3 flex-1">
          {item.categoryName && (
            <div className="text-xs text-blue-500 mb-1">
              {item.categoryName}
            </div>
          )}
          <h3 className="text-lg font-bold text-[#202020] line-clamp-2 mb-2">
            <HighlightText
              text={item.scienceName || "未命名"}
              keyword={searchKeyword}
            />
          </h3>
          {item.introduction && (
            <p className="text-xs text-[#666] line-clamp-3 leading-relaxed">
              <HighlightText text={item.introduction} keyword={searchKeyword} />
            </p>
          )}
        </div>
      </div>
    );
  };

  // 渲染网格
  const renderScienceList = () => {
    if (loading) {
      return Array(pageSize)
        .fill(0)
        .map((_, idx) => (
          <div key={idx} className="bg-white shadow-md flex flex-col">
            <Skeleton.Image style={{ width: "100%", height: 260 }} />
            <div className="p-2 flex-1">
              <Skeleton active paragraph={{ rows: 2 }} />
            </div>
          </div>
        ));
    }

    if (error) {
      return (
        <div className="col-span-full flex justify-center items-center py-10">
          <Alert message={error} type="error" showIcon />
        </div>
      );
    }

    if (scienceList.length === 0) {
      return (
        <div className="col-span-full flex justify-center items-center py-10">
          <Empty description="暂无科普内容" />
        </div>
      );
    }

    return scienceList.map(renderScienceItem);
  };

  return (
    <section>
      <div className="container mx-auto flex flex-col my-4 md:flex-col items-center justify-between h-full">
        {/* 面包屑 */}
        <div className={styles.breadcrumbContainer}>
          <Breadcrumb items={getBreadcrumbItems()} separator=">" />
        </div>

        <SearchBar
          width={800}
          targetPath="/quality"
          placeholder="质量科普搜索：食品安全、检测标准、设备维护"
          clearAfterSearch={true}
        />

        {/* 标题和分类 */}
        <div className="w-full my-2">
          <div className={styles.categoryContainer}>
            {renderCategoryButtons()}
          </div>
        </div>

        {/* 科普内容瀑布流 */}
        <div className={`w-full ${styles.masonryContainer}`}>
          {renderScienceList()}
        </div>

        {/* 无限滚动加载指示器 */}
        {loading && scienceList.length > 0 && (
          <div className="w-full flex justify-center py-8">
            <Spin size="large" />
          </div>
        )}

        {/* 加载更多触发器 */}
        {!loading && !error && scienceList.length < totalItems && (
          <div
            ref={loadMoreRef}
            className="w-full h-20 flex items-center justify-center"
          >
            <Spin size="large" />
          </div>
        )}

        {/* 视频播放模态框 */}
        <Modal
          title={selectedItem?.scienceName}
          open={isModalOpen}
          onCancel={handleModalClose}
          footer={null}
          width="50%"
          maxWidth="1200px"
          destroyOnHidden={true}
        >
          {selectedItem && (
            <>
              {/* 在 JSX 外部声明 videoUrl 变量 */}
              {(() => {
                const videoUrl = getVideoUrl();
                return (
                  <div>
                    <div className="text-sm text-gray-500 mb-4">
                      {selectedItem.categoryName && (
                        <span className="mr-4">
                          分类：{selectedItem.categoryName}
                        </span>
                      )}
                      上传时间：
                      {new Date(selectedItem.uploadTime).toLocaleString()}
                    </div>

                    {selectedItem.introduction && (
                      <div className="mb-4 text-gray-700">
                        <h4 className="font-bold mb-2">简介：</h4>
                        <p>{selectedItem.introduction}</p>
                      </div>
                    )}

                    <div className={styles.videoContainer}>
                      {videoLoading && (
                        <div className={styles.videoLoading}>
                          <Spin
                            indicator={<LoadingOutlined spin sizes="small" />}
                          />
                        </div>
                      )}

                      {videoUrl ? (
                        <video
                          ref={videoRef}
                          src={videoUrl}
                          controls
                          playsInline
                          muted
                          autoPlay
                          className="absolute top-0 left-0 w-full h-full"
                          onLoadStart={handleVideoLoadStart}
                          onLoadedData={handleVideoLoadedData}
                          onError={handleVideoError}
                          poster={
                            selectedItem.covers?.[0]?.attachmentAddress
                              ? getFullImageUrl(
                                  selectedItem.covers[0].attachmentAddress
                                )
                              : ""
                          }
                        >
                          您的浏览器不支持视频播放
                        </video>
                      ) : (
                        <div className="absolute top-0 left-0 w-full h-full flex items-center justify-center bg-gray-100">
                          <Alert
                            message="未找到可用视频"
                            type="warning"
                            showIcon
                          />
                        </div>
                      )}
                    </div>

                    {/* 显示所有附件链接 */}
                    {selectedItem.attachments?.length > 0 && (
                      <div className="mt-4">
                        <h4 className="font-bold mb-2">相关附件：</h4>
                        <ul className="list-disc pl-5">
                          {selectedItem.attachments.map((att, index) => (
                            <li key={index} className="mb-1">
                              <a
                                href={getFullImageUrl(att.attachmentAddress)}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="text-blue-500 hover:underline"
                              >
                                {att.attachmentName || `附件 ${index + 1}`}
                              </a>
                            </li>
                          ))}
                        </ul>
                      </div>
                    )}
                  </div>
                );
              })()}
            </>
          )}
        </Modal>
      </div>
    </section>
  );
}
